package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.entity.WmUser;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-02-10
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    private IApUserFollowService apUserFollowService;
    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public ResponseResult login(LoginDto dto) {
//        有两种情况：如果电话号码和密码都为空，就使用设备id
        if(dto==null || StringUtils.isBlank(dto.getEquipmentId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if(StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
//            就是根据手机号和密码登录的
//        2、根据名称查询用户  select * from ap_user where phone=?
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone,dto.getPhone());
            ApUser one = this.getOne(queryWrapper);
//              如果查不到 返回用户不存在的提示
            if(one==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AD_USER_DATA_NOT_EXIST);
            }
//         3、比较密码
//               如果密码不一致 返回密码错误的提示
//        再重新加密时注意再带上盐 one.getSalt()
//        把明文密码+one.getSalt() 通过md5加密后再和表中加密后的密码比较
            String password_page = DigestUtils.md5Hex(dto.getPassword() + one.getSalt());
            if (! StringUtils.equals(password_page,one.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

//        4、返回结果
//        {user:{},token:""}
            Map resultMap = new HashMap();
            one.setPassword(""); //去除敏感数据
            one.setSalt("");   //去除敏感数据
            one.setPhone("");  //去除敏感数据
            resultMap.put("user",one);

//        根据JWT生成token
            Map<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId",one.getId());
            claimMaps.put("name",one.getName());
            String token = AppJwtUtil.getToken(claimMaps);

            resultMap.put("token",token);

            return ResponseResult.okResult(resultMap);
        }else{
//            根据设备id生成token  userId设置成0

            //        4、返回结果
//        {user:{},token:""}
            ApUser one = new ApUser();
            one.setId(0);
            Map resultMap = new HashMap();
            resultMap.put("user",one);

//        根据JWT生成token
            Map<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId",one.getId());
            claimMaps.put("name","");
            String token = AppJwtUtil.getToken(claimMaps);
            resultMap.put("token",token);
            return ResponseResult.okResult(resultMap);
        }
    }

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {

        User user = UserThreadLocalUtil.get();
        if(user==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
//             * 0  关注
//             * 1  取消
        Integer operation = dto.getOperation();
        if(operation==0){

            ApUserFollow apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(user.getUserId());  //当前登录人
            apUserFollow.setUserName(user.getName());
            apUserFollow.setFollowId(dto.getAuthorId()); //文章作者
            //远程调用文章微服 获取文章作者的名字
            ResponseResult<ApAuthor> apAuthor = articleFeign.getApAuthor(dto.getAuthorId());
            apUserFollow.setFollowName(apAuthor.getData().getName());
            apUserFollow.setCreatedTime(new Date());
//            剩下的这5个先随便给一个值
            apUserFollow.setLevel(1);
            apUserFollow.setIsNotice(true);
            apUserFollow.setIsShieldComment(false);
            apUserFollow.setIsDisplay(true);
            apUserFollow.setIsShieldLetter(false);
            apUserFollowService.save(apUserFollow);
        }else{
//            delete from ap_user_follow where user_id=? and follow_id =?
            LambdaQueryWrapper<ApUserFollow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUserFollow::getUserId,user.getUserId());
            queryWrapper.eq(ApUserFollow::getFollowId,dto.getAuthorId());
            apUserFollowService.remove(queryWrapper);
        }
//            向Kafka中发送一条数据
//            谁（设备）对谁关注还是取消关注了  FollowBehaviorDto
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setFollowId(dto.getAuthorId());
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setOperation(dto.getOperation());
        kafkaTemplate.send("user_follow_behavior", JSON.toJSONString(followBehaviorDto));

        return ResponseResult.okResult();
    }
    @Autowired
    private KafkaTemplate kafkaTemplate;
}
